/*
 * @Description:
 * @Author: qingyang
 * @Date: 2022-04-19 13:51:25
 * @LastEditors: qingyang
 * @LastEditTime: 2022-11-23 11:07:20
 */
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { UserActionTypes } from '@/store/modules/user/action-types';
import { store } from '@/store';
import { UrlTokenParamsType, LoginFactory } from '@/hooks/LoginFactory.class';
import { getProtocolUrl } from '@/apis/user/user';
import { isString } from '@/utils/is';

export const useLogin = () => {
  const pageLoading = ref(false);
  const showLoginPage = ref(false);
  const privacyProtocol = ref(''); // 隐私协议
  const userProtocol = ref(''); // 用户协议
  const route = useRoute();
  const router = useRouter();

  /**
   * 获取协议
   */
  function getProtocols() {
    getProtocolUrl().then((res: any) => {
      privacyProtocol.value = res.privacyProtocol;
      userProtocol.value = res.userProtocol;
    });
  }

  /**
   * 确定登录平台（账号密码、eps等）
   */
  const checkLoginPlatform = async () => {
    console.log('checkLoginPlatform', route.query);
    const loginInstance = LoginFactory.GetInstanceByLocationQuery(route.query);
    if (loginInstance) {
      if (loginInstance.userType == 'SSO') {
        // 如果platform == oa,则手动跳转
        const redirectUri = encodeURIComponent(`${window.location.origin}/login?platform=OA`);
        window.location.href = `http://testoa.sokon.com/sso/login?appid=${window.OA_ID}&service=${redirectUri}`;
        return;
      }
      pageLoading.value = true;
      showLoginPage.value = false;
      try {
        await store.dispatch(UserActionTypes.ACTION_LOGIN, {
          userInfo: route.query as UrlTokenParamsType,
          loginType: 'SSO'
        });
        pageLoading.value = false;
        router.push('/');
      } catch (error) {
        console.log('error', error);
        pageLoading.value = false;
        setTimeout(() => {
          loginInstance.handleLogout();
        }, 2000);
      }
    } else {
      showLoginPage.value = true;
      pageLoading.value = false;
    }
  };
  return {
    pageLoading,
    showLoginPage,
    privacyProtocol,
    userProtocol,
    checkLoginPlatform
  };
};
